<script lang="ts" setup>
import { h, ref } from 'vue'

import { useVbenModal } from '@vben/common-ui'

import { useDebounceFn } from '@vueuse/core'
import { message, Spin } from 'ant-design-vue'

import { useVbenForm } from '#/adapter/form'
import { getWarehouseList } from '#/api/common'
import { splitOrder } from '#/api/spuBom'

const emit = defineEmits(['refresh'])
const keyword = ref('')
const fetching = ref(false)
const listData = ref([])

async function fetgetWareHouse({ keyword = '' }: Record<string, any>) {
  const { list } = await getWarehouseList({
    quick_search: keyword,
    page: 1,
    limit: 999,
    initKey: 'id',
    initValue: undefined,
    select: true,
  })
  return list.map((item: any) => ({
    label: item.code_name,
    value: item.id,
  }))
}

const [Form, formApi] = useVbenForm({
  handleSubmit: onSubmit,
  layout: 'vertical',
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
  },
  schema: [
    {
      component: 'Input',
      componentProps: {
        placeholder: '',
        disabled: true,
      },
      fieldName: 'warehouse_name',
      label: '建议退/收料仓库',
      rules: 'required',
    },
    {
      component: 'ApiSelect',
      componentProps: () => {
        return {
          api: fetgetWareHouse,
          // 禁止本地过滤
          filterOption: false,
          notFoundContent: fetching.value ? undefined : null,
          // 搜索词变化时记录下来， 使用useDebounceFn防抖。
          onSearch: useDebounceFn((value: string) => {
            keyword.value = value
          }, 300),
          // 远程搜索参数。当搜索词变化时，params也会更新
          params: {
            keyword: keyword.value || undefined,
          },
          showSearch: true,
          allowClear: true,
        }
      },
      fieldName: 'warehouse_id',
      label: '退/收料仓库',
      renderComponentContent: () => {
        return {
          notFoundContent: fetching.value ? h(Spin) : undefined,
        }
      },
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: '',
        disabled: true,
      },
      fieldName: 'price',
      label: '退收料单价',
      rules: 'required',
    },
    {
      component: 'InputNumber',
      componentProps: {
        placeholder: '',
      },
      fieldName: 'action_num',
      label: '拆分数量',
      rules: 'required',
    },
  ],
  showDefaultActions: false,
})

const [Modal, modalApi] = useVbenModal({
  fullscreenButton: false,
  onCancel() {
    modalApi.close()
  },
  onConfirm: async () => {
    await formApi.validateAndSubmitForm()
    // modalApi.close();
  },
  onOpenChange(isOpen: boolean) {
    if (!isOpen) return
    const { data } = modalApi.getData<Record<string, any>>()
    listData.value = data
    formApi.setValues(data, false)
  },
  title: '拆单-确认拆单',
})

async function onSubmit(values: Record<string, any>) {
  modalApi.lock()
  const from = await formApi.getValues()
  const parmas = {
    ...from,
    num: from.action_num,
    reviced_price: from.price,
    list_data: [listData.value],
  }
  splitOrder(parmas).then((res: any) => {
    modalApi.unlock()
    if (res.data.code === 1) {
      message.success(res.data.msg)
      emit('refresh')
    } else {
      message.error(res.data.msg)
    }
  })
}
</script>
<template>
  <Modal>
    <Form />
  </Modal>
</template>
